<?php

namespace app\modules\front\model;

use app\models\cacheModel\SettingModel;
use app\models\tableModel\UserModel;
use app\service\JwtService;

class UserLoginModel extends UserModel implements \yii\web\IdentityInterface
{

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {

        $admin_ = self::findOne(['id' => $id]);

        if (!empty($admin_)) return $admin_;

        return null;
    }

    /**
     * 以Token登录
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {

        ### 先解析JWT
        $jwtService = JwtService::loadModel(['jwt' => $token]);

        ### 根据JWT用户信息取出用户编号和用户信息
        $userId = $jwtService->getInfo('payload.user_info.id');
        if (!$userId) return false;
        $userRecord = self::findOne(['id' => $userId]);
        if (!$userRecord) return false;

        ### 验证JWT是否过期
        // 先赋值个人登录秘钥
        $jwtService->setAttributes(['secret' => $userRecord->getLoginSecret()],
            false);
        if (!$jwtService->validateAll()) return false;

        ### 先查找TOKEN
//        $tokenRecord = UserTokenModel::findOne(['token' => $token]);
//        if (empty($tokenRecord)) return null;
//        // 是否过期 -- 这里还是要验证数据库走数据库的，要做后台强制下线
//        if ($tokenRecord['expire'] < time()) return null;

        ### 再查找用户
        // $userRecord = self::findOne(['id' => $tokenRecord['user_id']]);

        return $userRecord;
    }

    /**
     * Finds user by username
     * @param $username
     * @return self|null
     */
    public static function findByUsername($username)
    {

        $admin_ = self::findOne(['user_name' => $username]);
        if (!empty($admin_)) return $admin_;

        return null;
    }

    /**
     *  Finds user by phone
     * @param $phone
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function findByMobile($phone)
    {

        $admin_ = self::findOne(['mobile' => $phone]);
        if (!empty($admin_)) return $admin_;

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return true;
    }

    /**
     * 获取登录秘钥
     * @return string
     */
    public function getLoginSecret() {
        return SettingModel::getSetting('user_login_secret') . '_' .
            $this->getAttribute('login_secret');
    }

    /**
     * Validates password
     * @param $password
     * @return bool
     */
    public function validatePassword($password)
    {

        $password = $this->getPwdCrypt($password, $this->salt);
        return $this->getAttribute('password') === $password;
    }
}
